<?php
/**
 * Created by PhpStorm.
 * User: Season
 * Date: 2018/6/13
 * Time: 22:24
 */

class temolate
{
    private $templateDir;
    private $compileDir;
    private $leftTag = '{#';
    private $rightTag = '#}';
    private $currentTemp = '';
    private $outputHtml = '';
    private $varPool =  array();

    public function __construct($templateDir,$compileDir,$leftTag = null,$rightTag = null)
    {
        $this->templateDir = $templateDir;
        $this->compileDir = $compileDir;
        if(!empty($leftTag)) $this->leftTag = $leftTag;
        if(!empty($rightTag)) $this->$rightTag = $rightTag;
    }

    public function assign($tag,$var){
        $this->varPool[$tag] = $var;
    }

    public function getVar($tag){
        return $this->varPool[$tag];
    }

    //获取模板源文件的代码
    public function  getSourceTemplate($templateName,$ext = '.html'){
        $this->currentTemp = $templateName;
        $sourceFilename = $this->templateDir.$this->currentTemp.$ext;
        $this->outputHtml = file_get_contents($sourceFilename);
    }

    //编译模板源代码
    public function compileTemplate($templatyeName = null,$ext = '.html'){
        $templatyeName = empty($templatyeName) ? $this->currentTemp : $templatyeName;
        //\{#\$(\w+)#\}
        $pattern = '/'.preg_quote($this->leftTag);
        $pattern .= ' *\$([a-zA-Z_]\w*) *';
        $pattern .= preg_quote($this->rightTag).'/';
        $this->outputHtml = preg_replace($pattern,'<?php echo $this->getVar(\'$1\') ?>',$this->outputHtml);
        $compiledFilename =  $this->compileDir.md5($templatyeName).$ext;
        file_put_contents($compiledFilename,$this->outputHtml);
    }

    public function  display($templateName = null,$ext = '.html'){
        $templatyeName = empty($templatyeName) ? $this->currentTemp : $templatyeName;
        include_once $this->compileDir.md5($templatyeName).$ext;
    }
}